var logger = require('./Logger'),
    config = require('../config').config,
    WechatMsg = require('../proxy/model/WechatMsg'),
    WechatText = require('../proxy/model/WechatText'),
    WeiXinApi = require('../lib/WeiXinApi'),
    Activity = require('../proxy').Activity,
    User = require('../proxy').User,
    redisManager =require('../proxy').RedisManager,
    dateUtil = require('../utils/DateUtil');

exports.messageRouter = function(req, res, next){
    _wechatReqHandle(req, res, function(msg){
        if(msg.event === 'CLICK'){
            switch (msg.eventKey) {
                case 'fanju_01':
                    console.log('fanju_01');
                    break;
                case 'fanju_02':
                    console.log("fanju_02");
                    break;
                case 'fanju_03':
                    console.log("fanju_03");
                    break;
                case 'fanju_04':
                    console.log("fanju_04");
                    break;
                default:
                    break;
            }
        }else if(msg.event == 'subscribe'){
            logger.debug('[ '+msg.fromUserName + ' ] Subscribe, Welcome!');
            //TODO: 引导信息
        }else if(msg.event == 'unsubscribe'){
            logger.debug('[ '+msg.fromUserName + ' ] Unsubscribe, Fuck shit!');
            //从用户缓存移除
            redisManager.removeUser(msg.fromUserName, function(err, data){
                if(err) return logger.error(err.message);
                logger.debug('['+msg.fromUserName+'] has removed from redisCache~')
            })
        }else{
            if(msg.msgType == 'text'){
                if(/^\d{4}$/.test(msg.content)){
                    _joinActivity(msg, function(err, data){
                        var picText = new WechatText();
                        if(err) return res.send(picText.getTextMsg(msg, '十分抱歉，服务器喝多了...呕吐中...'));
                        if(data){
                            if(data.outside) return res.send(picText.getTextMsg(msg, '你还没混入此圈子哦～'));
                            var content = ' 成功入局！ \n' +
                                '\n 聚会：'+data.name+'\n' +
                                '\n 发起人：'+data.creator.name+'\n' +
                                '\n 时间：'+dateUtil.getZhDate(data.startTime)+'(周'+dateUtil.getWeekday(data.startTime)+')\n' +
                                '\n 地点：'+data.location+'\n'+
                                '\n /:jj <a href=\'' + config.wechat_url + 'invite/'+data.id+'\'>查看详细</a> \n'
                            return res.send(picText.getTextMsg(msg, content))
                        }else{
                            var content = '没找到该聚会，想攒饭局？\n' +
                                '\n /:jj <a href=\'' + config.wechat_url + 'create\'>点击立刻发起</a> \n';
                            return res.send(picText.getTextMsg(msg, content))
                        }
                    });
                }
            }else if(msg.msgType == 'image'){
                console.log('imge not support yet！')
                return res.send(picText.getTextMsg(msg, '图片就不客气的收下了～'))
            }
        }
    });
}
/**
 * 封装微信消息
 * @param req
 * @param res
 * @param callback
 * @private
 */
function _wechatReqHandle(req, res, callback){
    var buf = '';
    req.setEncoding('utf8');
    req.on('data', function(chunk){
        buf += chunk;
    });
    req.on('end', function(){
        var msg = new WechatMsg(buf);
        logger.debug(msg);
        callback(msg);
    });
}

function _joinActivity(msg, callback){
    redisManager.getUser(msg.fromUserName, function(err, user){
        if(user){
            User.getUserById(user.id, function(err, user){
                Activity.joinActivity(msg.content, user, function(err, data){
                    callback(err, data);
                });
            })
        }else{
            redisManager.getAccesstoken(function(err, token){
                WeiXinApi.getUserInfo(token, msg.fromUserName, function(err, userInfo){
                    User.newAndSave(
                        userInfo.nickname,
                        (userInfo.sex === 1 ?'male':'female'),
                        userInfo.city,
                        userInfo.province,
                        userInfo.country,
                        userInfo.openid,
                        userInfo.headimgurl, function(err, data){
                        Activity.joinActivity(msg.content, data, function(err, data){
                            callback(err, data);
                        });
                    });
                })
            })
        }
    })
}